<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :inline="true" :model="queryParams" label-width="68px">
          <el-form-item label="电梯名称" prop="elevatorName">
            <el-input v-model="queryParams.elevatorName" clearable placeholder="请输入电梯名称" style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:upkeepPlan:add']" icon="Plus" plain type="primary" @click="handleAdd">新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:upkeepPlan:edit']" :disabled="single" icon="Edit" plain type="success" @click="handleUpdate()"
              >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:upkeepPlan:remove']" :disabled="multiple" icon="Delete" plain type="danger" @click="handleDelete()"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['iot:upkeepPlan:export']" icon="Download" plain type="warning" @click="handleExport">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="upkeepPlanList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" label="电梯名称" prop="elevatorName" />
        <el-table-column align="center" label="模板名称" prop="templateName" />
        <el-table-column align="center" label="保养类型" prop="upkeepType">
          <template #default="scope">
            <dict-tag :options="iot_upkeep_type" :value="scope.row.upkeepType" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="保养间隔" prop="upkeepInterval" />
        <el-table-column align="center" label="首次保养时间" prop="firstUpkeepTime" />
        <el-table-column align="center" label="最近一次保养时间" prop="recentlyTime" />
        <el-table-column align="center" label="保养提醒天数" prop="remindDay" />
        <el-table-column align="center" label="备注" prop="remark" />
        <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['iot:upkeepPlan:edit']" icon="Edit" link type="primary" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['iot:upkeepPlan:remove']" icon="Delete" link type="primary" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改电梯保养计划对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" append-to-body width="500px">
      <el-form ref="upkeepPlanFormRef" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="电梯名称" prop="elevatorId">
          <el-select v-model="form.elevatorId" filterable placeholder="请选择电梯" style="width: 240px">
            <el-option v-for="item in elevatorList" :key="item.elevatorId" :label="item.elevatorName" :value="item.elevatorId" />
          </el-select>
        </el-form-item>
        <el-form-item label="模板名称" prop="templateId">
          <el-select v-model="form.templateId" filterable placeholder="请选择模板" style="width: 240px">
            <el-option v-for="item in templateList" :key="item.templateId" :label="item.templateName" :value="item.templateId" />
          </el-select>
        </el-form-item>
        <el-form-item label="保养类型" prop="upkeepType">
          <el-select v-model="form.upkeepType" filterable placeholder="请选择保养类型" style="width: 240px" @change="upkeepChange">
            <el-option v-for="item in iot_upkeep_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="保养间隔天数" prop="upkeepInterval">
          <el-input v-model="form.upkeepInterval" disabled placeholder="请输入保养间隔" style="width: 200px" />
        </el-form-item>
        <el-form-item label="首次保养时间" prop="firstUpkeepTime">
          <el-date-picker v-model="form.firstUpkeepTime" placeholder="请输入首次保养时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="最近一次保养时间" prop="recentlyTime">
          <el-date-picker v-model="form.recentlyTime" placeholder="请输入最近一次保养时间" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item label="保养提醒天数" prop="remindDay">
          <el-input v-model="form.remindDay" placeholder="请输入保养提醒天数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="UpkeepPlan" setup>
import { addUpkeepPlan, delUpkeepPlan, getUpkeepPlan, listUpkeepPlan, updateUpkeepPlan } from "@/api/iot/upkeepPlan";
import { UpkeepPlanForm, UpkeepPlanQuery, UpkeepPlanVO } from "@/api/iot/upkeepPlan/types";
import { listElevator } from "@/api/iot/elevator";
import { listUpkeepTemplate } from "@/api/iot/upkeepTemplate";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_project_type, iot_upkeep_type } = toRefs<any>(proxy?.useDict("iot_project_type", "iot_upkeep_type"));
const upkeepPlanList = ref<UpkeepPlanVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const elevatorList = ref<Array<any>>([]);
const templateList = ref<Array<any>>([]);

const queryFormRef = ref<ElFormInstance>();
const upkeepPlanFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const initFormData: UpkeepPlanForm = {
  planId: undefined,
  elevatorId: undefined,
  templateId: undefined,
  upkeepType: undefined,
  upkeepInterval: undefined,
  firstUpkeepTime: undefined,
  recentlyTime: undefined,
  remindDay: undefined,
  remark: undefined
};
const data = reactive<PageData<UpkeepPlanForm, UpkeepPlanQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    elevatorId: undefined,
    templateId: undefined,
    upkeepType: undefined,
    upkeepInterval: undefined,
    firstUpkeepTime: undefined,
    recentlyTime: undefined,
    remindDay: undefined,
    elevatorName: undefined,
    params: {}
  },
  rules: {
    planId: [
      { required: true, message: "计划ID不能为空", trigger: "blur" }
    ],
    elevatorId: [
      { required: true, message: "关联电梯ID不能为空", trigger: "blur" }
    ],
    templateId: [
      { required: true, message: "关联模板ID不能为空", trigger: "blur" }
    ],
    upkeepType: [
      { required: true, message: "保养类型不能为空", trigger: "change" }
    ],
    upkeepInterval: [
      { required: true, message: "保养间隔不能为空", trigger: "blur" }
    ],
    firstUpkeepTime: [
      { required: true, message: "首次保养时间不能为空", trigger: "blur" }
    ],
    recentlyTime: [
      { required: true, message: "最近一次保养时间不能为空", trigger: "blur" }
    ],
    remindDay: [
      { required: true, message: "保养提醒天数不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询电梯保养计划列表 */
const getList = async () => {
  loading.value = true;
  const res = await listUpkeepPlan(queryParams.value);
  upkeepPlanList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  upkeepPlanFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: UpkeepPlanVO[]) => {
  ids.value = selection.map(item => item.planId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加电梯保养计划";
};

/** 修改按钮操作 */
const handleUpdate = async (row?: UpkeepPlanVO) => {
  reset();
  const _planId = row?.planId || ids.value[0];
  const res = await getUpkeepPlan(_planId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改电梯保养计划";
};

/** 提交按钮 */
const submitForm = () => {
  upkeepPlanFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.planId) {
        await updateUpkeepPlan(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addUpkeepPlan(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: UpkeepPlanVO) => {
  const _planIds = row?.planId || ids.value;
  await proxy?.$modal.confirm("是否确认删除电梯保养计划编号为\"" + _planIds + "\"的数据项？").finally(() => loading.value = false);
  await delUpkeepPlan(_planIds);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download("iot/upkeepPlan/export", {
    ...queryParams.value
  }, `upkeepPlan_${new Date().getTime()}.xlsx`);
};
const upkeepChange = (e: any) => {
  if (e === "1") {
    form.value.upkeepInterval = 15;
  } else if (e === "2") {
    form.value.upkeepInterval = 90;
  } else if (e === "3") {
    form.value.upkeepInterval = 180;
  } else if (e === "4") {
    form.value.upkeepInterval = 365;
  }
};
onMounted(async () => {
  await getList();
  let res = await listElevator();
  elevatorList.value = res.rows;
  let res2 = await listUpkeepTemplate();
  templateList.value = res2.rows;
});
</script>
